package services

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/gorilla/mux"
	"gokit/util"
	"net/http"
	"strconv"
)

func DecodeUserRequest(_ context.Context, r *http.Request) (interface{}, error) { //这个函数决定了使用哪个request结构体来请求
	vars := mux.Vars(r)
	//if r.URL.Query().Get("uid") != "" {
	//	uid, _ := strconv.Aoi(r.URL.Query().Get("uid"))
	//	return UserRequest{Uid: uid}, nil
	//}

	if uid, ok := vars["uid"]; ok {
		_uid, _ := strconv.Atoi(uid)
		return UserRequest{
			Uid:    _uid,
			Method: r.Method,
			Token:  r.URL.Query().Get("token"),
		}, nil
	}
	return nil, errors.New("参数错误")
}

func EncodeUserResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
	w.Header().Set("Content-type", "application/json") //设置响应格式为json，这样客户端接收到的值就是json，就是把我们设置的UserResponse给json化了

	return json.NewEncoder(w).Encode(response) //判断响应格式是否正确
}

// MyErrorEncoder 自定义错误处理
func MyErrorEncoder(_ context.Context, err error, w http.ResponseWriter) {
	contentType, body := "text/plain, charset=utf-8", []byte(err.Error())
	w.Header().Set("content-type", contentType)
	if myErr, ok := err.(*util.MyError); ok {
		w.WriteHeader(myErr.Code) // 设置错误状态码
	} else {
		w.WriteHeader(http.StatusInternalServerError)
	}
	_, _ = w.Write(body)
}
